<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('编辑')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="标签名称" prop="name">
        <el-input v-model="dataForm.label" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="备注">
        <el-input v-model="dataForm.remark" placeholder=""></el-input>
      </el-form-item>
      <el-form-item prop="sort" label="排序">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0"
          :label="$t('menu.sort')"></el-input-number>
      </el-form-item>
      <el-form-item prop="openStyle" label="是否显示">
        <el-radio-group v-model="dataForm.delFlag">
          <el-radio :label="0">显示</el-radio>
          <el-radio :label="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  label: "",
  sort: 255,
  remark: "",
  delFlag: 0,
  creator: "",
  createDate: "",
  updater: "",
  updateDate: "",
});

const init = (labelId?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (labelId) {
    getInfo(labelId);
  }
};



// 获取信息
const getInfo = (labelId: number) => {
  baseService.get("/crm/crmlabel/" + labelId).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/crm/crmlabel", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};


defineExpose({
  init
});
</script>
